﻿package net.wangit.framework.validation;

import java.io.File;

import net.wangit.LabelUtil;
import net.wangit.context.ActionContext;
import net.wangit.context.LocalContext;
import net.wangit.context.MultiPartRequestWrapper;
import net.wangit.framework.config.UploadConfig;
import net.wangit.framework.config.UploadSettings;
import net.wangit.support.Validator;
import net.wangit.util.Checker;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;


public class FileValidator implements Validator {

	private static final Log log = LogFactory
			.getLog(net.wangit.framework.dispatcher.DispatcherServlet.class);
	private String inputName;

	public FileValidator(String inputName) {
		this.inputName = inputName;
	}

	public String validate(ActionContext ac, String value, String expression,
			int rowIndex) {
		javax.servlet.http.HttpServletRequest request = LocalContext
				.getLocalContext().getHttpServletRequest();
		if (!(request instanceof MultiPartRequestWrapper))
			return LabelUtil.get(ac, "system", "upload.enctype");
		UploadConfig config;
		if (Checker.isEmpty(expression))
			config = UploadSettings.getConfig();
		else
			try {
				config = new UploadConfig(expression);
			} catch (Exception e) {
				return LabelUtil.get(ac, "system", "upload.expression");
			}
		File file = ac.getFiles(inputName)[rowIndex];
		String fileName = ac.getRequestParameter(rowIndex, (new StringBuilder(
				String.valueOf(inputName))).append("filename").toString());
		String contentType = ac.getRequestParameter(rowIndex,
				(new StringBuilder(String.valueOf(inputName))).append(
						"contenttype").toString());
		if (file != null && fileName != null && contentType != null)
			return validateFile(ac, file, fileName, contentType, config);
		else
			return null;
	}

	public String validate(ActionContext ac, String from, String to, String s) {
		return null;
	}

	protected String validateFile(ActionContext ac, File file, String filename,
			String contentType, UploadConfig config) {
		if (config.getMaxSize() < file.length()) {
			String params[] = { Long.toString(file.length()),
					Long.toString(config.getMaxSize()) };
			return LabelUtil.get(ac, "system", "upload.too.large", params);
		}
		if (!config.isAllowedType(contentType))
			return LabelUtil.get(ac, "system",
					"upload.content.type.not.allowed", contentType);
		if (!config.isAllowedExtension(filename)) {
			String extension = "null";
			int index = filename.indexOf(".");
			if (index > 0)
				extension = filename.substring(index + 1);
			return LabelUtil.get(ac, "system", "upload.extension.not.allowed",
					extension);
		} else {
			return null;
		}
	}

}
